package com.huaju.web.controller;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.ws.rs.core.HttpHeaders;

import org.apache.commons.httpclient.util.DateUtil;
import org.aspectj.weaver.Dump.INode;
import org.hibernate.type.IdentifierType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.task.TaskExecutor;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.huaju.enity.Account;
import com.huaju.enity.AllListBean;
import com.huaju.enity.Incomelist;
import com.huaju.enity.Notice;
import com.huaju.enity.Payoutlist;
import com.huaju.enity.Paytype;
import com.huaju.enity.Profit;
import com.huaju.manager.WebMananger;
import com.jinzht.tools.MessageType;
import com.jinzht.tools.MsgUtil;
import com.wx.tools.AKConfig;
import com.wx.tools.DateUtils;
import com.wx.tools.FileUtil;
import com.wx.tools.MessageBean;
import com.wx.tools.Tools;
import com.wx.tools.wx.TestWChatPayToUser;

@Controller
public class WebController extends BaseController {

	@Autowired
	private WebMananger webManager;

/*	@Autowired
	private TaskExecutor executor;*/

	/***
	 * ---------------------------------------------小程序Account
	 * API-------------------- -----------------------
	 ***/

	@RequestMapping("/App/verifyCode")
	@ResponseBody
	/***
	 * 发送验证码
	 * @param message MessageBean数据校验bean
	 * @param bindingResult 校验绑定结果
	 * @param session HttpSession
	 * @return
	 */
	public Map verifyCode(MessageBean message, Model model, HttpSession session) {
		this.result = new HashMap();
		this.result.put("data", "");
		this.message = "";
		String content = AKConfig.STRING_SMS_REGISTE;
		MsgUtil SMS = new MsgUtil(message.getTelephone(), content, MessageType.VerifyCode);
		// 获取用户输入手机号码是否已经存在
		Account user = this.webManager.getAccountDAO().findUserByTelephone(
				message.getTelephone());
		if (user != null) {
			// 发送验证码
			Integer code = 0;
			if (message.getTelephone().equalsIgnoreCase("18729342354")) {
//				code = MsgUtil.send();
				code = 6868;

			} else {
				code = MsgUtil.send();
//				code = 6868;
			}

			// 测试 1234
			if (code != 0) {
				this.status = 200;
				if (this.message.equals("")) {
					this.message = AKConfig.SMS_HAVE_SEND_STRING;
				}
				session.setAttribute("code", code);
				System.out.println(session.getAttribute("code"));
			} else {
				this.status = 400;
				this.message = AKConfig.SMS_FAIL_SEND_STRING;
			}
		} else {
			this.status = 400;
			this.message = "该用户不存在，请联系管理员!";
		}
		System.out.println("code:" + session.getAttribute("code"));
		this.result.put("data", "JSESSIONID=" + session.getId());
		return getResult();
	}

	@RequestMapping("/App/loginUser")
	@ResponseBody
	/***
	 * 用户登录
	 * @param userInstance 传参
	 * @param bindingResult 校验结果绑定
	 * @param session HttpSession
	 * @return 返回值
	 */
	public Map loginUser(@RequestParam(value = "telephone") String telePhone,
			@RequestParam(value = "verifyCode") String verifyCode,
			@RequestParam(value = "openId") String openId,
			@RequestParam(value = "model") String model,
			HttpServletRequest request, HttpSession session) {

		System.out.println("code:" + session.getAttribute("code"));
		this.result = new HashMap();
		this.result.put("data", "");
		if (telePhone.equals(null) || telePhone.equals("")) {
			this.status = 400;
			this.message = AKConfig.STRING_LOGING_TEL_NOT_NULL;
		} else {
			// 开始校验密码
			Account user = this.webManager.getAccountDAO().findUserByTelephone(
					telePhone);
			if (user != null) {
				session.setAttribute("userId", user.getAid());
			}
			if (telePhone.equalsIgnoreCase("18729342354")) {
				session.setAttribute("code", 6868);
			}
			if (session.getAttribute("code") != null) {
				String code = session.getAttribute("code").toString();

				if (code.equalsIgnoreCase(verifyCode)) {
					if (openId != null && !openId.equalsIgnoreCase("")) {
						user.setOpenId(openId);
					}
					if (model != null) {
						user.setPhoneModel(model);
					}
					this.webManager.getAccountDAO().saveOrUpdate(user);
					// // 返回结果
					Map map = new HashMap();
					map.put("userId", user.getAid());

					this.status = 200;
					this.result.put("data", map);
					this.message = AKConfig.STRING_LOGING_SUCCESS;
					session.setAttribute("userId", user.getAid());
				} else {
					// 更新登录失败信息
					this.status = 400;
					this.message = AKConfig.STRING_LOGING_CODE_ERROR;
				}
			} else {
				// 登录失败记录添加
				this.status = 400;
				this.result.put("data", "");
				this.message = AKConfig.STRING_LOGING_CODE_NOT_GET;
			}

		}
		return getResult();
	}

	@RequestMapping("/App/isLoginUser")
	@ResponseBody
	/***
	 * 检查用户是否已登录
	 * @param mm
	 * @param session
	 * @return
	 */
	public Map isLoginUser(ModelMap mm, HttpSession session) {
		this.result = new HashMap();

		this.status = 200;
		this.result.put("data", "");
		this.message = AKConfig.STRING_LOGING_STATUS_ONLINE;

		// 检测用户是否已登录
		System.out.println("获取到Session :UserId："
				+ session.getAttribute("userId"));

		if (session.getAttribute("userId") == null) {
			this.status = 400;
			this.message = AKConfig.STRING_LOGING_STATUS_OFFLINE;
		} else {
			Account user = this.findUserInSession(session);
			if (user != null) {
				this.status = 200;
				this.result.put("data", user.getAid());
			} else {
				this.status = 400;
				this.message = AKConfig.STRING_LOGING_STATUS_OFFLINE;
			}

		}
		return getResult();
	}

	// @RequestMapping("/requestUserRankingList")
	// @ResponseBody
	// /***
	// * 获取排行榜
	// * @param page
	// * @param session
	// * @return
	// */
	// public Map requestUserRankingList(
	// @RequestParam(value = "page") Integer page, HttpSession session) {
	// this.result = new HashMap();
	//
	// // 获取用户
	// User user = this.findUserInSession(session);
	//
	// List list = null;
	// if (user != null) {
	// Authentic authentic = this.authenticManager
	// .findAuthenticByUserId(user.getUserId());
	//
	// if (authentic.getIdentity() == null) {
	// Identity identity = new Identity();
	// identity.setIdentiyTypeId(1);
	//
	// authentic.setIdentity(identity);
	// }
	// // 根据用户身份类型获取排行榜
	// list = this.authenticManager.findRankingByIdentitype(
	// authentic.getIdentity(), page, 10);
	// } else {
	// list = new ArrayList();
	// }
	//
	// this.status = 200;
	// this.result.put("data", list);
	// this.message = "";
	// return getResult();
	// }

	@RequestMapping("/App/getUserInfo")
	@ResponseBody
	/***
	 * 获取用户信息
	 * @param session
	 * @return
	 */
	public Map getUserInfo(HttpSession session) {
		this.result = new HashMap();

		// 获取用户
		Account user = this.findUserInSession(session);
		// user = this.userManger.findUserById(2);
		if (user != null) {
			user.setLastloginTime(new Date());
			this.webManager.getAccountDAO().saveOrUpdate(user);

			user.setPwd(null);
			user.setCreatetime(null);
			user.setLastloginTime(null);

			this.status = 200;
			this.message = "";
			this.result.put("data", user);
		} else {

			this.status = 201;
			this.message = "请重新登录";
		}
		return getResult();
	}

	@RequestMapping("/App/AutoLogin")
	@ResponseBody
	/***
	 * 微信openID自动登录信息
	 * @param session
	 * @return
	 */
	public Map autoLogin(HttpSession session,
			@RequestParam(value = "openId") String openId) {
		this.result = new HashMap();
		if (openId != null) {
			List<Account> list = this.webManager.getAccountDAO()
					.findByProperty("openId", openId);
			if (list != null && list.size() > 0) {
				Account user = list.get(0);

				session.setAttribute("userId", user.getAid());
				this.status = 200;
				// this.result.put("data", user);
				this.message = "";
			} else {
				this.status = 400;
				// this.result.put("data", user);
				this.message = "";
			}

		} else {
			this.status = 400;
			this.message = "";
		}

		return getResult();
	}

	@RequestMapping("/App/loginOut")
	@ResponseBody
	/***
	 * 微信openID自动登录信息
	 * @param session
	 * @return
	 */
	public Map loginOut(HttpSession session) {
		this.result = new HashMap();
		session.setAttribute("userId", "-1");
		this.status = 200;
		this.message = "";

		return getResult();
	}

	@RequestMapping("/App/getUserBalance")
	/**
	 * 获取用户余额，总收入，总支出信息
	 * @param session
	 * @return
	 */
	@ResponseBody
	public Map getUserBalance(@RequestParam(value = "type") Integer type,
			HttpSession session) {
		this.result = new HashMap();
		Account user = this.findUserInSession(session);

		if (user != null) {
			System.out.println("uid:" + user.getAid());
			// 所有收入
			Double allcome = 0.00;
			allcome = this.webManager.getIncomeListDAO().getAllIncomeByUser(
					user.getAid());
			// 所有支出
			Double allpay = 0.00;
			allpay = this.webManager.getPayoutListDAO().getAllPayoutByUser(
					user.getAid(), type);
			// 总收益利息
			Double incomePro = 0.00;
			incomePro = this.webManager.getProfitDAO().getIncomeProfitByUser(
					user.getAid(), type);
			// 总支出利息
			Double payPro = 0.00;
			payPro = this.webManager.getProfitDAO().getPayProfitByUser(
					user.getAid(), type);
			// 现有利息
			Double nowPro = incomePro - payPro;

			// 当前余额（本金）
			Double balance = allcome - allpay;

			// 当前余额（本金）
			Double allBalance = allcome - allpay + nowPro;

			// 昨日收益
			Double yestdatPro = this.webManager.getProfitDAO()
					.findLastDayIncome(user.getAid());

			// 最新收入
			List<Incomelist> ilist = this.webManager.getIncomeListDAO()
					.findUserIncomeByPage(0, 2, user.getAid());

			// 最新支出
			List<Payoutlist> plist = this.webManager.getPayoutListDAO()
					.findUserIncomeByPage(0, 2, user.getAid());

			// 最新收益
			List<Profit> prolist = this.webManager.getProfitDAO()
					.findUserIncomeByPage(0, 2, user.getAid());

			List allList = getUserAllList(ilist, plist, prolist);

			List<Notice> noticeList = this.webManager.getNoticeDAO()
					.findUserUnReadNoticeByPage(0, 3, user.getAid());

			this.status = 200;
			// this.result.put("data", list);
			this.result.put("balance", DecimalFormat(balance));
			this.result.put("allBalance", DecimalFormat(allBalance));
			this.result.put("allIncome", DecimalFormat(allcome));
			this.result.put("allpay", DecimalFormat(allpay));
			this.result.put("nowPro", DecimalFormat(nowPro));
			this.result.put("yestdatPro", DecimalFormat(yestdatPro));
			this.result.put("incomePro", DecimalFormat(incomePro));
			this.result.put("payPro", DecimalFormat(payPro));

			this.result.put("noticeList", noticeList);
			this.result.put("data", allList);

		} else {
			this.status = 400;
			// this.result.put("data", list);
			this.message = "未登录";
		}
		// List<Incomelist> list =
		// this.webManager.getIncomeListDAO().findByProperty("aid", id);
		// Double allcome = 0.00;
		// for(Incomelist i:list){
		// allcome += i.getImoney();
		// }

		return getResult();
	}

	private List getUserAllList(List<Incomelist> ilist, List<Payoutlist> plist,
			List<Profit> prolist) {
		List<AllListBean> list = new ArrayList<AllListBean>();
		for (Incomelist i : ilist) {
			AllListBean a = new AllListBean();
			a.setDesc(i.getIdesc());
			a.setId(i.getIid());
			a.setMoney(DecimalFormat(i.getImoney()));
			a.setTime(i.getSuccessTime());
			if (i.getSuccessTime() != null) {
				a.setTime2(DateUtils.getStringDate(i.getSuccessTime()));
			} else {
				a.setTime2("");
			}
			a.setType(1);
			a.setSuccess(i.getSuccess());
			list.add(a);
		}
		for (Payoutlist i : plist) {
			AllListBean a = new AllListBean();
			a.setDesc(i.getPdesc());
			a.setId(i.getPid());
			a.setMoney(DecimalFormat(i.getPmoney()));
			a.setTime(i.getPtime());
			if (i.getSuccessTime() != null) {
				a.setTime2(DateUtils.getStringDate(i.getSuccessTime()));
			} else {
				a.setTime2("");
			}
			a.setType(2);
			a.setSuccess(i.getSuccess());
			list.add(a);
		}
		for (Profit i : prolist) {
			AllListBean a = new AllListBean();
			a.setDesc(i.getIdesc());
			a.setId(i.getPid());
			a.setMoney(DecimalFormat(i.getImoney()));
			if (i.getSuccessTime() != null) {
				a.setTime2(DateUtils.getStringDate(i.getSuccessTime()));
			} else {
				a.setTime2("");
			}
			a.setTime(i.getItime());
			a.setType(i.getPaytype().getPid());
			a.setSuccess(i.getSuccess());
			a.setType(3);
			list.add(a);
		}
		Collections.sort(list);
		return list;
	}

	@RequestMapping("/App/getUserIncomList")
	/**
	 * 获取用户收入
	 * @param session
	 * @return
	 */
	@ResponseBody
	public Map getUserIncomList(@RequestParam(value = "page") Integer page,
			@RequestParam(value = "size") Integer size, HttpSession session) {
		this.result = new HashMap();
		Account user = this.findUserInSession(session);
		if (user != null) {
			// 收入列表
			try {
				List<Incomelist> list = this.webManager.getIncomeListDAO()
						.findUserIncomeByPage(page, size, user.getAid());

				for (Incomelist i : list) {
					i.setMoneyStr(DecimalFormat(i.getImoney()));
				}
				if (list == null || list.size() == 0) {
					if (page == 0) {
						this.status = 201;
						this.message = "暂无数据";
						this.result.put("data", list);
					} else {
						this.status = 201;
						this.message = "没有更多数据了";
						this.result.put("data", list);
					}
				} else {
					this.status = 200;
					this.message = "";
					this.result.put("data", list);
				}
			} catch (Exception e) {
				this.status = 400;
				this.message = "参数错误！";
			}
		} else {
			this.status = 400;
			this.message = "未登录";
		}
		return getResult();
	}

	@RequestMapping("/App/getUserIncomeById")
	/**
	 * 获取用户收入
	 * @param session
	 * @return
	 */
	@ResponseBody
	public Map getUserIncomeById(@RequestParam(value = "id") Integer id,
			HttpSession session) {
		this.result = new HashMap();
		Account user = this.findUserInSession(session);
		if (user != null) {
			Incomelist incomelist = this.webManager.getIncomeListDAO()
					.findById(id);
			incomelist.setMoneyStr(DecimalFormat(incomelist.getImoney()));
			if (incomelist != null) {
				this.status = 200;
				this.result.put("data", incomelist);

				this.message = "";
			} else {
				this.status = 201;
				this.message = "未找到该记录";
			}
		} else {
			this.status = 400;
			this.message = "未登录";
		}
		return getResult();
	}

	@RequestMapping("/App/getUserIncomLastDayList")
	/**
	 * 获取用户收入  前几天数据
	 * @param session
	 * @return
	 */
	@ResponseBody
	public Map getUserIncomLastDayList(
			@RequestParam(value = "day") Integer day,

			HttpSession session) {
		this.result = new HashMap();
		Account user = this.findUserInSession(session);
		if (user != null) {
			// 收入列表
			try {
				List<Incomelist> list = this.webManager.getIncomeListDAO()
						.findLastDayList(day);
				this.status = 200;
				this.message = "";
				this.result.put("data", list);

			} catch (Exception e) {
				this.status = 400;
				this.message = "参数错误！";
			}
		} else {
			this.status = 400;
			this.message = "未登录";
		}
		return getResult();
	}

	@RequestMapping("/App/getUserPayOutList")
	/**
	 * 获取用户支出列表
	 * @param session
	 * @return
	 */
	@ResponseBody
	public Map getUserPayOutList(@RequestParam(value = "page") Integer page,
			@RequestParam(value = "size") Integer size, HttpSession session) {
		this.result = new HashMap();
		Account user = this.findUserInSession(session);
		if (user != null) {
			// 收入列表
			try {
				List<Payoutlist> list = this.webManager.getPayoutListDAO()
						.findUserIncomeByPage(page, size, user.getAid());
				for (Payoutlist i : list) {
					i.setMoneyStr(DecimalFormat(i.getPmoney()));
				}
				if (list == null || list.size() == 0) {
					if (page == 0) {
						this.status = 201;
						this.message = "暂无数据";
						this.result.put("data", list);
					} else {
						this.status = 201;
						this.message = "没有更多数据了";
						this.result.put("data", list);
					}
				} else {
					this.status = 200;
					this.message = "";
					this.result.put("data", list);
				}
			} catch (Exception e) {
				this.status = 400;
				this.message = "参数错误！";
			}
		} else {
			this.status = 400;
			this.message = "未登录";
		}
		return getResult();
	}

	@RequestMapping("/App/getUserPayById")
	/**
	 * 获取用户收入
	 * @param session
	 * @return
	 */
	@ResponseBody
	public Map getUserPayById(@RequestParam(value = "id") Integer id,
			HttpSession session) {
		this.result = new HashMap();
		Account user = this.findUserInSession(session);
		if (user != null) {
			Payoutlist incomelist = this.webManager.getPayoutListDAO()
					.findById(id);
			if (incomelist != null) {
				incomelist.setMoneyStr(DecimalFormat(incomelist.getPmoney()));
				this.status = 200;
				this.result.put("data", incomelist);
				this.message = "";
			} else {
				this.status = 201;
				this.message = "未找到该记录";
			}
		} else {
			this.status = 400;
			this.message = "未登录";
		}
		return getResult();
	}

	@RequestMapping("/App/getUserPayOutLastDayList")
	/**
	 * 获取用户收入  前几天数据
	 * @param session
	 * @return
	 */
	@ResponseBody
	public Map getUserPayOutLastDayList(
			@RequestParam(value = "day") Integer day,

			HttpSession session) {
		this.result = new HashMap();
		Account user = this.findUserInSession(session);
		if (user != null) {
			// 收入列表
			try {
				List<Incomelist> list = this.webManager.getIncomeListDAO()
						.findLastDayList(day);
				this.status = 200;
				this.message = "";
				this.result.put("data", list);

			} catch (Exception e) {
				this.status = 400;
				this.message = "参数错误！";
			}
		} else {
			this.status = 400;
			this.message = "未登录";
		}
		return getResult();
	}

	@RequestMapping("/App/getUserProIncomeList")
	/**
	 * 获取用户收益
	 * @param page
	 * @param size
	 * @param type  null/-1:全部收益列表；5：余额收益；3,4余额提现
	 * @param session
	 * @return
	 */
	@ResponseBody
	public Map getUserProIncomeList(@RequestParam(value = "page") Integer page,
			@RequestParam(value = "size") Integer size,
			@RequestParam(value = "type", required = false) Integer type,
			HttpSession session) {
		this.result = new HashMap();
		Account user = this.findUserInSession(session);
		if (user != null) {
			// 收入列表
			try {
				if (type == null) {
					type = -1;
				}
				List<Profit> list = this.webManager.getProfitDAO()
						.findListByType(page, size, type, user.getAid());
				for (Profit i : list) {
					i.setMoneyStr(DecimalFormat(i.getImoney()));
				}
				if (list == null || list.size() == 0) {
					if (page == 0) {
						this.status = 201;
						this.message = "暂无数据";
						this.result.put("data", list);
					} else {
						this.status = 201;
						this.message = "没有更多数据了";
						this.result.put("data", list);
					}
				} else {
					this.status = 200;
					this.message = "";
					this.result.put("data", list);
				}
			} catch (Exception e) {
				this.status = 400;
				this.message = "参数错误！";
			}
		} else {
			this.status = 400;
			this.message = "未登录";
		}
		return getResult();
	}

	@RequestMapping("/App/getUserProLastDayList")
	/**
	 * 获取用户收入  前几天数据
	 * @param session
	 * @return
	 */
	@ResponseBody
	public Map getUserProLastDayList(@RequestParam(value = "day") Integer day,

	HttpSession session) {
		this.result = new HashMap();
		Account user = this.findUserInSession(session);
		if (user != null) {
			// 收入列表
			try {
				List<Incomelist> list = this.webManager.getProfitDAO()
						.findLastDayList(day, user.getAid());
				this.status = 200;
				this.message = "";
				this.result.put("data", list);
			} catch (Exception e) {
				this.status = 400;
				this.message = "参数错误！";
			}
		} else {
			this.status = 400;
			this.message = "未登录";
		}
		return getResult();
	}

	@RequestMapping("/App/getUserProfitById")
	/**
	 * 获取用户收入
	 * @param session
	 * @return
	 */
	@ResponseBody
	public Map getUserProfitById(@RequestParam(value = "id") Integer id,
			HttpSession session) {
		this.result = new HashMap();
		Account user = this.findUserInSession(session);
		if (user != null) {
			Profit incomelist = this.webManager.getProfitDAO().findById(id);
			if (incomelist != null) {
				incomelist.setMoneyStr(DecimalFormat(incomelist.getImoney()));
				this.status = 200;
				this.result.put("data", incomelist);
				this.message = "";
			} else {
				this.status = 201;
				this.message = "未找到该记录";
			}
		} else {
			this.status = 400;
			this.message = "未登录";
		}
		return getResult();
	}

	@RequestMapping("/App/OrderToDrawInit")
	/**
	 * 用户发起本金提现订单
	 * @param money
	 * @param toType   1;提现到零钱；2提现到银行卡
	 * @param session
	 * @return
	 */
	@ResponseBody
	public Map OrderToDrawInit(HttpSession session) {
		this.result = new HashMap();
		Account user = this.findUserInSession(session);
		// 验证登录
		if (user != null) {
			List<Payoutlist> listP = this.webManager.getPayoutListDAO()
					.findApplyItems("account", user);
			List<Profit> listO = this.webManager.getProfitDAO().findApplyItems(
					"account", user);
			if (listP != null && listP.size() > 0) {
				this.status = 200;
				this.result.put("data", listP.size() > 0 ? listP.get(0) : null);
			} else if (listO != null && listO.size() > 0) {
				this.status = 200;
				this.result.put("data", listO.size() > 0 ? listO.get(0) : null);

			} else {
				this.status = 201;
			}

			this.message = "数据获取成功";

		} else {
			this.status = 400;
			this.message = "用户未登录！";
		}
		return getResult();
	}

	@RequestMapping("/App/OrderToDrawIncome")
	/**
	 * 用户发起本金提现订单
	 * @param money
	 * @param toType   1;提现到零钱；2提现到银行卡
	 * @param session
	 * @return
	 */
	@ResponseBody
	public Map OrderToDrawIncomeMoney(
			@RequestParam(value = "money") Double money,
			@RequestParam(value = "toType") Integer toType,
			@RequestParam(value = "openId") String openId, HttpSession session) {
		this.result = new HashMap();
		if (money != null && money > 0) {
			Account user = this.findUserInSession(session);
			// 验证登录
			if (user != null) {
				if (openId == null) {
					openId = user.getOpenId();
				}
				// 所有收入
				Double allcome = 0.00;
				allcome = this.webManager.getIncomeListDAO()
						.getAllIncomeByUser(user.getAid());
				// 所有支出
				Double allpay = 0.00;
				allpay = this.webManager.getPayoutListDAO().getAllPayoutByUser(
						user.getAid(), 1);

				BigDecimal b1 = new BigDecimal(allcome);

				BigDecimal b2 = new BigDecimal(allpay.toString());
				// 当前余额（本金）
				Double allBalance = b1.subtract(b2).doubleValue();
				System.out.println(allcome);
				System.out.println(allpay);
				System.out.println(money);
				System.out.println(DecimalFormat(allBalance));
				String payResult = "";
				String desc = "";
				String payCode = "";
				if (money <= allBalance) {
					Payoutlist drowPay = new Payoutlist();
					drowPay.setAccount(user);
					drowPay.setPmoney(money);
					drowPay.setSuccess((short) 0);
					drowPay.setPtime(new Date());
					drowPay.setOpenId(openId);
					// drowPay.setSuccessTime(new Date());
					drowPay.setToType(toType);
					if (user.getComId() != null) {
						drowPay.setComId(user.getComId());
					}

					desc = "";
					// 提现到零钱
					String payResultStr = "";
					desc = user.getName() + "本金提现到零钱";
					payCode = "GZUSER" + DateUtils.getStringALLDay(new Date());
					drowPay.setPayCode(payCode);

					if (toType == 1) {
						Paytype paytype = this.webManager.getPayTypeDAO()
								.findById(1);
						drowPay.setPaytype(paytype);

						drowPay.setPdesc(desc + ":" + money + ",订单：" + payCode);
					} else {
						Paytype paytype = this.webManager.getPayTypeDAO()
								.findById(2);
						drowPay.setPaytype(paytype);
						drowPay.setPdesc(desc + ":" + money + ",订单：" + payCode);
					}
					boolean result = this.webManager.getPayoutListDAO().save(
							drowPay);
					if (result) {
						this.status = 200;
						this.message = "提现成功！";
						this.result.put("data", drowPay);

					} else {
						this.status = 203;
						this.message = "提现失败！数据库操作错误";
					}

				} else {
					this.status = 201;
					this.message = "用户余额不足！";
				}
			} else {
				this.status = 400;
				this.message = "用户未登录！";
			}
		} else {
			this.status = 400;
			this.message = "参数错误！";
		}
		return getResult();
	}

	@RequestMapping("/App/OrderToDrawProfit")
	/**
	 * 用户发起余额提现订单
	 * @param session
	 * @return
	 */
	@ResponseBody
	public Map OrderToDrawProfitMoney(
			@RequestParam(value = "money") Double money,
			@RequestParam(value = "toType") Integer toType,
			@RequestParam(value = "openId") String openId, HttpSession session) {
		this.result = new HashMap();
		if (money != null && money > 0) {
			Account user = this.findUserInSession(session);
			// 验证登录
			if (user != null) {
				if (openId == null) {
					openId = user.getOpenId();
				}
				// 总收益利息
				Double incomePro = 0.00;
				incomePro = this.webManager.getProfitDAO()
						.getIncomeProfitByUser(user.getAid(), 1);
				// 总支出利息
				Double payPro = 0.00;
				payPro = this.webManager.getProfitDAO().getPayProfitByUser(
						user.getAid(), 1);
				// 现有利息
				BigDecimal b1 = new BigDecimal(incomePro);
				BigDecimal b2 = new BigDecimal(payPro.toString());
				// 当前余额（本金）
				Double nowPro = b1.subtract(b2).doubleValue();
				String payResult = "";
				String desc = "";
				String payCode = "";
				if (money <= nowPro) {
					Profit drowPay = new Profit();
					drowPay.setAccount(user);
					drowPay.setImoney(money);
					
					Paytype type = new Paytype();
					type.setPid(1);

					drowPay.setPaytype(type);
					drowPay.setItime(new Date());
					drowPay.setSuccess((short) 0);
					drowPay.setOpenId(openId);

					// drowPay.setSuccessTime(new Date());
					drowPay.setToType(toType);
					if (user.getPosition() != null) {
						drowPay.setComId(user.getComId());
					}

					desc = user.getName() + "余额提现到零钱";
					payCode = "GZUSER" + DateUtils.getStringALLDay(new Date());
					drowPay.setPayCode(payCode);
					if (toType == 3) {
						Paytype paytype = this.webManager.getPayTypeDAO()
								.findById(3);
						drowPay.setPaytype(paytype);
						drowPay.setIdesc(desc + ":" + money + ",订单：" + payCode);
					} else {
						Paytype paytype = this.webManager.getPayTypeDAO()
								.findById(4);
						drowPay.setPaytype(paytype);
						drowPay.setIdesc(desc + ":" + money + ",订单：" + payCode);
					}
					boolean result = this.webManager.getProfitDAO().save(
							drowPay);
					if (result) {
						this.status = 200;
						this.message = "提现成功！";
					} else {
						this.status = 203;
						this.message = "提现失败！数据库操作错误";
					}
				} else {
					this.status = 201;
					this.message = "用户余额不足！";
				}
			} else {
				this.status = 400;
				this.message = "用户未登录！";
			}
		} else {
			this.status = 400;
			this.message = "参数错误！";
		}
		return getResult();
	}

	@RequestMapping("/App/getUserNoticeList")
	/**
	 * 获取用户通知列表
	 * @param session
	 * @return
	 */
	@ResponseBody
	public Map getUserNoticeList(@RequestParam(value = "page") Integer page,
			@RequestParam(value = "size") Integer size, HttpSession session) {
		this.result = new HashMap();
		Account user = this.findUserInSession(session);
		if (user != null) {
			try {
				List<Notice> list = this.webManager.getNoticeDAO()
						.findUserNoticeByPage(page, size, user.getAid());
				if (list == null || list.size() == 0) {
					if (page == 0) {
						this.status = 201;
						this.message = "暂无数据";
						this.result.put("data", list);
					} else {
						this.status = 201;
						this.message = "没有更多数据了";
						this.result.put("data", list);
					}
				} else {
					this.status = 200;
					this.message = "";
					this.result.put("data", list);
				}
			} catch (Exception e) {
				this.status = 400;
				this.message = "参数错误！";
			}
		} else {
			this.status = 400;
			this.message = "未登录";
		}
		return getResult();
	}

	@RequestMapping("/App/getUserUnReadNoticeList")
	/**
	 * 获取用户通知列表
	 * @param session
	 * @return
	 */
	@ResponseBody
	public Map getUserUnReadNoticeList(
			@RequestParam(value = "page") Integer page,
			@RequestParam(value = "size") Integer size, HttpSession session) {
		this.result = new HashMap();
		Account user = this.findUserInSession(session);
		if (user != null) {
			try {
				List<Notice> list = this.webManager.getNoticeDAO()
						.findUserUnReadNoticeByPage(page, size, user.getAid());
				if (list == null || list.size() == 0) {
					if (page == 0) {
						this.status = 201;
						this.message = "暂无数据";
						this.result.put("data", list);
					} else {
						this.status = 201;
						this.message = "没有更多数据了";
						this.result.put("data", list);
					}
				} else {
					this.status = 200;
					this.message = "";
					this.result.put("data", list);
				}
			} catch (Exception e) {
				this.status = 400;
				this.message = "参数错误！";
			}
		} else {
			this.status = 400;
			this.message = "未登录";
		}
		return getResult();
	}

	@RequestMapping("/App/getUserNoticeById")
	/** 
	 * 获取用户通知
	 * @param session
	 * @return
	 */
	@ResponseBody
	public Map getUserNoticeById(@RequestParam(value = "id") Integer id,
			HttpSession session) {
		this.result = new HashMap();
		Account user = this.findUserInSession(session);
		if (user != null) {
			try {
				Notice notice = this.webManager.getNoticeDAO().findById(id);
				if (notice == null) {
					this.status = 201;
					this.message = "暂无数据";
					this.result.put("data", "");

				} else {
					this.status = 200;
					this.message = "";
					this.result.put("data", notice);
				}
			} catch (Exception e) {
				this.status = 400;
				this.message = "参数错误！";
			}
		} else {
			this.status = 400;
			this.message = "未登录";
		}
		return getResult();
	}

	@RequestMapping("/App/updateNoticeReadById")
	/** 
	 * 跟新用户已读通知
	 * @param session
	 * @return
	 */
	@ResponseBody
	public Map updateNoticeReadById(@RequestParam(value = "id") Integer id,
			HttpSession session) {
		this.result = new HashMap();
		Account user = this.findUserInSession(session);
		if (user != null) {
			try {
				Notice notice = this.webManager.getNoticeDAO().findById(id);
				if (notice == null) {
					this.status = 201;
					this.message = "未找到该通知！";
					this.result.put("data", "");

				} else {
					notice.setIsRead(1);
					this.webManager.getNoticeDAO().attachDirty(notice);
					this.status = 200;
					this.message = "修改成功";
					this.result.put("data", "");
				}
			} catch (Exception e) {
				this.status = 400;
				this.message = "参数错误！";
			}
		} else {
			this.status = 400;
			this.message = "未登录";
		}
		return getResult();
	}

	/***
	 * 从当前session获取用户对象
	 * 
	 * @param session
	 * @return
	 */
	private Account findUserInSession(HttpSession session) {
		Account user = null;
		if (session.getAttribute("userId") != null) {
			// Integer userId = Tools.findUserBySession(session);
			try {
				Integer userId = (Integer) session.getAttribute("userId");
				user = this.webManager.getAccountDAO().findById(userId);
			} catch (Exception e) {
				// TODO: handle exception
				return user;
			}

		}

		return user;
	}

	/***
	 * ---------------------------------------------后端管理 API--------------------
	 * -----------------------
	 ***/

	@RequestMapping(value = "/newSystem/adminLogin")
	public String loginAction(
			@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "password", required = false) String password,
			HttpSession session, ModelMap map) {
		map.put("account", name);
		map.put("content", "content");
		map.put("menu", 0);
		map.put("submenu", 0);
		return AKConfig.NEW_SERVER_CONTROL;
	}

	/***
	 * 首页
	 * 
	 * @param map
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "newSystem/index")
	public String requestIndexPage(ModelMap map, HttpSession session) {

		map.put("content", "content");
		map.put("menu", 0);
		map.put("submenu", 0);
		return AKConfig.NEW_SERVER_CONTROL;
	}

	@RequestMapping(value = "/test")
	@ResponseBody
	public Map requestFeelingDetail(
			@RequestParam(value = "id", required = true) Integer id,

			HttpSession session) {
		this.result = new HashMap();
		Double allcome = 0.00;
		allcome = this.webManager.getIncomeListDAO().getAllIncomeByUser(id);
		this.status = 200;
		// this.result.put("data", list);
		this.result.put("allIncome", allcome);
		return getResult();
	}

	@RequestMapping(value = "/add")
	@ResponseBody
	public Map add(HttpSession session) {
		this.result = new HashMap();

		Incomelist l = new Incomelist();
		Account account = this.webManager.getAccountDAO().findById(1);
		l.setAccount(account);
		l.setImoney(1.00);
		l.setItime(new Date());
		this.webManager.getIncomeListDAO().save(l);
		this.status = 200;
		return getResult();
	}

	/*@RequestMapping(value = "/add2")
	@ResponseBody
	public Map add2(HttpSession session) {
		this.result = new HashMap();

		// 线程池+同步块
		executor.execute(new Runnable() {
			@Override
			public void run() {
				synchronized (webManager) {
					Incomelist l = new Incomelist();
					Account account = webManager.getAccountDAO().findById(1);
					l.setAccount(account);
					l.setImoney(1.00);
					l.setItime(new Date());
					webManager.getIncomeListDAO().save(l);
				}
			}
		});
		this.status = 200;
		return getResult();
	}*/

	private String DecimalFormat(Double oldDouble) {
		if (oldDouble == null) {
			return null;
		}

		return new DecimalFormat("###########0.00").format(oldDouble);

	}

	private void main2() {

	}

}
